package com.groupbuying.provider.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.groupbuying.provider.connector.SettleFeign;
import com.groupbuying.provider.constants.CommonConstants;
import com.groupbuying.provider.constants.StoreAccountEnumConstants;
import com.groupbuying.provider.context.FilterContextHandler;
import com.groupbuying.provider.dao.*;
import com.groupbuying.provider.domain.*;
import com.groupbuying.provider.dto.convert.AccountConvert;
import com.groupbuying.provider.dto.AccountDTO;
import com.groupbuying.provider.dto.StoreAccountDTO;
import com.groupbuying.provider.dto.forManage.LoginDTO;
import com.groupbuying.provider.dto.forManage.StoreCapitalVirtualAccountDetaiDTO;
import com.groupbuying.provider.dto.forManage.StoreRoleDO;
import com.groupbuying.provider.service.StoreAccountService;
import com.groupbuying.provider.service.StoreMenuService;
import com.groupbuying.provider.utils.*;
import com.groupbuying.provider.utils.apiresult.ApiResult;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ywxd
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class StoreAccountServiceImpl implements StoreAccountService {

    @Autowired
    StoreAccountDao accountMapper;
    @Autowired
    StoreAccountRoleDao accountRoleMapper;
    @Autowired
    StoreCheckoutCounterRelDao storeCheckoutCounterRelDao;
    @Autowired
    StoreCheckoutCounterDao storeCheckoutCounterDao;
    @Autowired
    StoreShopDao storeShopDao;
    @Autowired
    StoreCapitalVirtualAccountDao storeCapitalVirtualAccountDao;
    @Autowired
    SettleFeign settleFeign;
    @Autowired
    StoreCapitalVirtualAccountDetailDao storeCapitalVirtualAccountDetailDao;
    @Autowired
    StoreMenuService storeMenuService;
    @Autowired
    StoreAccountRoleDao storeAccountRoleDao;
    @Autowired
    StoreRoleDao storeRoleDao;

    private static final Logger logger = LoggerFactory.getLogger(StoreAccountService.class);

    @Override
    public StoreAccountDO get(String id) {
        List<BigInteger> roleIds = accountRoleMapper.listRoleId(id);
        StoreAccountDO storeAccountDO = accountMapper.get(id);
        storeAccountDO.setRoleIds(roleIds);
        return storeAccountDO;
    }
    @Override
    public List<StoreAccountDO> list(Map<String, Object> map) {
        List<StoreAccountDO> resultList = accountMapper.list(map);
        for (StoreAccountDO item : resultList) {
            //1:正常,2:待审核,3审核驳回
            if (item.getStatus().equals("1")) {
                item.setStatus("审核通过");
            } else if (item.getStatus().equals("2")) {
                item.setStatus("待审核");
            } else if (item.getStatus().equals("3")) {
                item.setStatus("审核驳回");
            }
        }
        return resultList;
    }
    @Override
    public List<StoreAccountDTO> getStoreAndAgentName(Map<String, Object> map) {
        List<StoreAccountDTO> resultList = accountMapper.getStoreAndAgentName(map);
        logger.info("返回的信息是：{}",resultList);
        return resultList;

    }
    @Override
    public Map<String, StoreAccountDO> getMapByUuids(List<String> accountUuids) {

        Map<String, StoreAccountDO> map = new HashMap<String, StoreAccountDO>();
        if (accountUuids == null || accountUuids.size() <= 0) {
            return map;
        }

        Map<String, Object> params = new HashMap<>();
        params.put("accountIds", accountUuids);
        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);

        List<StoreAccountDO> list = accountMapper.getListByUuids(params);
        if (CollectionUtils.isNotEmpty(list) && list.size() > 0) {
            list.forEach(m -> {
                map.put(m.getAccountId(), m);
            });
        }

        return map;
    }


    @Override
    public int countForMinList(Map<String, Object> map) {
        return accountMapper.countForMinList(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return accountMapper.count(map);
    }

    @Override
    public boolean exits(Map<String, Object> params) {
        boolean exits = accountMapper.list(params).size() > 0;
        return exits;
    }

    @Override
    public ApiResult getUshop() {
        //String accountId = params.get("accountId").toString();
        String accountId = FilterContextHandler.getUserID();
        StoreCheckoutCounterRelDO storeCheckoutCounterRelDO = null;
        StoreShopDO storeShop = null;
        String checkstandId = null;
        String storeuuid = null;
        if (StringUtils.isEmpty(accountId)) {
            logger.error("账户ID获取失败");
            return ApiResult.failure("账户ID获取失败");

        }
        storeCheckoutCounterRelDO = storeCheckoutCounterRelDao.getUshop(accountId);
        if (storeCheckoutCounterRelDO == null) {
            logger.error("收银台商户关联表获取失败");
            return ApiResult.failure("收银台商户关联表获取失败");
        }
        checkstandId = storeCheckoutCounterRelDO.getCounteruuid();
        StoreCheckoutCounterDO storeCheckoutCounterDO = storeCheckoutCounterDao.get(checkstandId);
        if (storeCheckoutCounterDO == null) {
            logger.error("收银台查询失败");
            return ApiResult.failure("收银台查询失败");
        }
        storeuuid = storeCheckoutCounterDO.getStoreuuid();
        storeShop = storeShopDao.getStoreShop(storeuuid);
        logger.info("商户ID:{},收银台ID{}", storeuuid, checkstandId);

        Date date = new Date();
        long time = date.getTime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String format = formatter.format(calendar.getTime());
        logger.info("日期为" + format);
        Map<String, Object> map = new HashMap();
        BigDecimal flowStore = storeCapitalVirtualAccountDao.getByStorUUid(storeuuid);
        BigDecimal storeTodayFlow = settleFeign.getStoreTodayIncomeByCheckstandId(checkstandId);
        map.put("storeTodayFlow", storeTodayFlow);
        map.put("virtualaccount", flowStore);
        map.put("storeShop", storeShop);
        return ApiResult.success(map);
    }

    @Override
    public ApiResult getFlowStore(Map<String, String> map) {
        String parStart = map.get("gmtCreateStart");
        String parEnd = map.get("gmtCreateEnd");
        String checkstandId = null;
        String storeUuid = null;
        String accountId = FilterContextHandler.getUserID();

        StoreCheckoutCounterRelDO storeCheckoutCounterRelDO = storeCheckoutCounterRelDao.getUshop(accountId);
        if (storeCheckoutCounterRelDO != null) {
            checkstandId = storeCheckoutCounterRelDO.getCounteruuid();
        }
        logger.info("收银台ID" + checkstandId);
        StoreCheckoutCounterDO storeCheckoutCounterDO = storeCheckoutCounterDao.get(checkstandId);
        if (storeCheckoutCounterDO != null) {
            storeUuid = storeCheckoutCounterDO.getStoreuuid();

        }
        Map<String, Object> queryMap = new HashMap<>();
        if (!StringUtils.isEmpty(parStart) && !StringUtils.isEmpty(parEnd)) {
            //格式化开始时间
            parStart = DateUtils.format(new Date(Long.valueOf(parStart)), DateUtils.YMD);
            //传入的结束时间增加一天用于between查询的后开问题
            parEnd = DateUtils.format(new Date(Long.valueOf(parEnd) + 24 * 60 * 60 * 1000), DateUtils.YMD);
            queryMap.put("gmtCreateStart", parStart);
            queryMap.put("gmtCreateEnd", parEnd);
        }
        String[] inOrOut = {"0", "1","3"};

        queryMap.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        queryMap.put("storeUuid", storeUuid);
        queryMap.put("inOrOut", inOrOut);
        queryMap.put("page",map.get("page"));
        queryMap.put("limit",map.get("limit"));
        Query query = new Query(queryMap);

        List<StoreCapitalVirtualAccountDetaiDTO> storeCapitalVirtualAccountDetail = new ArrayList<>();
        List<StoreCapitalVirtualAccountDetailDO> storeCapitalVirtualAccountDetailList = storeCapitalVirtualAccountDetailDao.getStoreFlowListByStoreUuid(query);
        StoreCapitalVirtualAccountDetaiDTO dto = null;
        for (StoreCapitalVirtualAccountDetailDO store : storeCapitalVirtualAccountDetailList) {
            dto = new StoreCapitalVirtualAccountDetaiDTO(store);
            storeCapitalVirtualAccountDetail.add(dto);
        }


        int total = storeCapitalVirtualAccountDetailDao.countForFlow(query);
        PageUtils pageUtils = new PageUtils(storeCapitalVirtualAccountDetail, total);
        return ApiResult.success(pageUtils);
    }

    @Override
    public R internal_login(@Valid LoginDTO loginDTO) {
        String username = loginDTO.getUsername().trim();
        String password = loginDTO.getPwd().trim();
        password = MD5Utils.encrypt(username, password);
        StoreAccountDO accountDO = this.getByAccountName(username);
        logger.info("该账号的详细信息,该账号的状态:{},{}",accountDO,accountDO.getFreezestatus());
        if (null == accountDO) {
            return R.error("该用户不存在");
        }
        if(("1").equals(accountDO.getFreezestatus())){
            return  R.error("该账号已冻结");
        }
        if (!accountDO.getPassword().equals(password)) {
            return R.error("密码错误");
        }
        String agentId = accountDO.getAgentId();

        String status = accountDO.getStatus();
        if (!"00000".equals(agentId)) {
            if (!StoreAccountEnumConstants.ENUM_STATUS_NORMAL.equals(status)) {
                return R.error("服务商未审核通过");
            }
        }

        UserToken userToken = new UserToken(accountDO.getAccountName(), accountDO.getAccountId(), accountDO.getProviderId(), accountDO.getAgentId());

        String token = "";
        try {
            token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 60 * 60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 首先清除用户缓存权限
        // menuService.clearCache(userDO.getAccountId());
        // String token = tokenService.createToken(userDO.getUserId());

        return R.ok("登录成功")
                .put("token", token)
                .put("perms", storeMenuService.PermsByUserId(accountDO.getAccountId()))
                .put("router", storeMenuService.RouterDTOsByUserId(accountDO.getAccountId()));
    }

    @Override
    public StoreAccountDO getByAccountName(String accountName) {
        Map map_repeat = new HashMap();
        map_repeat.put("accountName", accountName);
        List<StoreAccountDO> list_repeat = accountMapper.list(map_repeat);
        if (list_repeat.size() > 0) {
            return list_repeat.get(0);
        }
        return null;
    }

    @Override
    public R internal_getStaffListLike(Map<String, Object> params) {
        try {
            params.put("delFlag", CommonConstants.COMMON_FLAG_UNDEL);
            params.put("status", CommonConstants.COMMON_STATE_UES);
            params.put("providerId", FilterContextHandler.getName());
            Query query = new Query(params);
            List<AccountDTO> userDTOS = AccountConvert.MAPPER.dos2dtos((this.listLike(query)));

            for (AccountDTO accountDTO : userDTOS) {
                List<BigInteger> roleIds = storeAccountRoleDao.listRoleId(accountDTO.getAccountId());
                StoreRoleDO storeRoleDO = storeRoleDao.get(roleIds.get(0));
                accountDTO.setRoleName(storeRoleDO.getRoleName());
            }
            int total = userDTOS.size();
            PageUtils pageUtil = new PageUtils(userDTOS, total);
            return R.ok().put("page", pageUtil);
        } catch (Exception e) {
            return R.error();
        }
    }

    @Override
    public List<StoreAccountDO> listLike(Map<String, Object> map) {
        List<StoreAccountDO> resultList = accountMapper.listLike(map);
        for (StoreAccountDO item : resultList) {
            //1:正常,2:待审核,3审核驳回
            if (item.getStatus().equals("1")) {
                item.setStatus("审核通过");
            } else if (item.getStatus().equals("2")) {
                item.setStatus("待审核");
            } else if (item.getStatus().equals("3")) {
                item.setStatus("审核驳回");
            }
        }
        return resultList;
    }

    @Override
    public R internal_getStaffList_unBangDing(Map<String, Object> params) {
        try {
            params.put("delFlag", CommonConstants.COMMON_FLAG_UNDEL);
            params.put("status", CommonConstants.COMMON_STATE_UES);
            params.put("providerId", FilterContextHandler.getName());
            Query query = new Query(params);
            List<AccountDTO> userDTOS = AccountConvert.MAPPER.dos2dtos((this.list(query)));
            List<AccountDTO> result_dto = new ArrayList<>();
            for (int i = 0; i < userDTOS.size(); i++) {
                AccountDTO accountDTO = userDTOS.get(i);
                List<StoreCheckoutCounterRelDO> relList = storeCheckoutCounterRelDao.getByAccount(accountDTO.getAccountId());
                if (relList.size() == 0) {
                    //已经关联收银台的不展示
                    result_dto.add(accountDTO);
                }
            }

            int total = userDTOS.size();
            PageUtils pageUtil = new PageUtils(result_dto, total);
            return R.ok().put("page", pageUtil);
        } catch (Exception e) {
            return R.error();
        }
    }

}
